package com.shengyin.ec.controller.payment;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.shengyin.ec.exception.ControllerException;
import com.shengyin.ec.model.entity.Payment;
import com.shengyin.ec.service.delivery.DelieveryService;
import com.shengyin.ec.service.payment.PaymentService;

@Controller
public class PaymentController {
	@Autowired
	PaymentService paymentService;

	@RequestMapping("/toPaymentAdd.do")
	public String toPaymentAdd() {

		return "redirect:/admin/payment/paymentAdd.jsp";
	}

	@RequestMapping("/toPaymentModify.do")
	public String toPaymentModify(Model model,@RequestParam("id") long id) {
		Payment payment  =paymentService.getPaymentById(id);
		model.addAttribute("payment", payment);
		return "/admin/payment/paymentModify";
	}

	@RequestMapping("/toPaymentList.do")
	public String toPaymentList(Model model) {
		List<Payment> paymentList = paymentService.getPaymentList();
		model.addAttribute("paymentList", paymentList);
		return "/admin/payment/paymentList";
	}

	@RequestMapping("/paymentAdd.do")
	public String createPayment(PaymentForm paymentForm) {

		try {
			Payment payment = new Payment();
			BeanUtils.copyProperties(payment, paymentForm);
			paymentService.createPayment(payment);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "redirect:/toPaymentList.do";
	}

	@RequestMapping("/paymentDelete.do")
	public String deletePayment(@RequestParam("id") int id) {
		paymentService.removePaymentById(id);
		return "redirect:/toPaymentList.do";
	}

	@RequestMapping("/paymentModify.do")
	public String modifyPayment(PaymentForm paymentForm) {
		try {
			Payment payment = new Payment();
			BeanUtils.copyProperties(payment, paymentForm);
			paymentService.modifyPayment(payment);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return "redirect:/toPaymentList.do";
	}

	  /*
     * spring mvc异常处理方法，在controller发生异常，可以以抛出ControllerException，以供捕获
     * */
    @ExceptionHandler({ControllerException.class})  
	   public String exception(ControllerException e,HttpServletRequest request) {  
	       request.setAttribute("error", e.getMessage());
	        return "/admin/error/error";  
	    }  
}
